package com.example.netcomponent.net.download;

import android.content.Context;
import android.text.TextUtils;

import com.example.netcomponent.BuildConfig;
import com.example.netcomponent.net.AppConstant;
import com.example.netcomponent.net.CommonApiService;
import com.example.netcomponent.net.utils.FileUtils;
import com.example.netcomponent.net.utils.LogUtils;
import com.example.netcomponent.net.utils.SpUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by zengxianghui900 on 17/10/11.
 */

public class HttpDownloadManager {

    private volatile static HttpDownloadManager INSTANCE;
    private ProgressDownloadSubscriber mSubscriber;

    //私有构造
    private HttpDownloadManager(){}
    //提供访问的公共方法
    public static HttpDownloadManager getInstance(){
        if (INSTANCE == null){
            synchronized (HttpDownloadManager.class){
                INSTANCE = new HttpDownloadManager();
            }
        }
        return INSTANCE;
    }

    public void startDownload(Context context, String url, final File file, HttpDownOnNextListener listener){

        mSubscriber = new ProgressDownloadSubscriber(listener);
        //创建一个okhttpClient builder对象
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //设置debug时日志打印
//        if (BuildConfig.DEBUG) {
            builder.addInterceptor(getHttpLoggingInterceptor());
//        }
        //添加读取token的interceptor
        builder.addInterceptor(new HttpDownloadManager.ReadTookenInterceptor(context));

        //设置进度回调拦截
        builder.addInterceptor(new DownloadInterceptor(mSubscriber));

        //创建retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .client(builder.build())    //添加定义好的OkHttpClient
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(getBaseUrl())
                .build();

        CommonApiService apiService = retrofit.create(CommonApiService.class);

        apiService.downloadApk(url)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .map(new Func1<ResponseBody, InputStream>() {
                    @Override
                    public InputStream call(ResponseBody responseBody) {
                        return responseBody.byteStream();
                    }
                })
                .observeOn(Schedulers.computation())
                .doOnNext(new Action1<InputStream>() {
                    @Override
                    public void call(InputStream inputStream) {
                        try {
                            FileUtils.writeFile(inputStream, file);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                })
                /*回调线程*/
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(mSubscriber);

    }

    /**
     * 根据documentId下载文件
     * @param url
     * @param file
     * @param listener
     */
    public void downloadByDocumentId(Context context,String url,final File file, HttpDownOnNextListener listener){

        mSubscriber = new ProgressDownloadSubscriber(listener);
        //创建一个okhttpClient builder对象
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //设置debug时日志打印
        if (BuildConfig.DEBUG) {
            builder.addInterceptor(getHttpLoggingInterceptor());
        }
        //添加读取token的interceptor
        builder.addInterceptor(new HttpDownloadManager.ReadTookenInterceptor(context));

        //设置进度回调拦截
        builder.addInterceptor(new DownloadInterceptor(mSubscriber));

        //创建retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .client(builder.build())    //添加定义好的OkHttpClient
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(getBaseUrl())
                .build();

        CommonApiService apiService = retrofit.create(CommonApiService.class);

//        apiService.downloadByDocumentId(url)
//                .subscribeOn(Schedulers.io())
//                .unsubscribeOn(Schedulers.io())
//                .map(new Func1<ResponseBody, InputStream>() {
//                    @Override
//                    public InputStream call(ResponseBody responseBody) {
//                        return responseBody.byteStream();
//                    }
//                })
//                .observeOn(Schedulers.computation())
//                .doOnNext(new Action1<InputStream>() {
//                    @Override
//                    public void call(InputStream inputStream) {
//                        try {
//                            FileUtils.writeFile(inputStream, file);
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                })
//                /*回调线程*/
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(mSubscriber);

    }


    /**
     * 添加token的拦截器
     * @return
     */
    public class ReadTookenInterceptor implements Interceptor {
        private Context mContext;
        public ReadTookenInterceptor(Context context) {
            mContext = context;
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request.Builder builder = chain.request().newBuilder();

            String token = SpUtils.getStringValue(mContext, AppConstant.SpKey.TOKEN);
            //登录的时候不需要添加请求头
            if (!TextUtils.isEmpty(token)) {
                builder.addHeader("token", token);
                LogUtils.e("OkHttp", "Adding Header: " + token); // This is done so I know which headers are being added; this interceptor is used after the normal logging of OkHttp
            }
            return chain.proceed(builder.build());
        }
    }


    /**
     * 获取基础网址（所有请求地址前面相同的部分）
     * 根据是否是debug包自动配置
     * @return
     */
    private String getBaseUrl() {
        return CommonApiService.BASE_URL;
    }


    /**
     * 日志输出
     * 自行判定是否添加
     * @return
     */
    private HttpLoggingInterceptor getHttpLoggingInterceptor(){
        //日志显示级别
        HttpLoggingInterceptor.Level level= HttpLoggingInterceptor.Level.BASIC;
        //新建log拦截器
        HttpLoggingInterceptor loggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                LogUtils.e("Retrofit====Message:"+message);
                LogUtils.saveLogToSD(LogUtils.ERROR_DOWNFILE,"Retrofit====Message:"+message);
            }

        });
        loggingInterceptor.setLevel(level);
        return loggingInterceptor;
    }

    /**
     * 取消下载
     */
    public void cancelDownload() {
        if(mSubscriber != null && !mSubscriber.isUnsubscribed()){
            mSubscriber.unsubscribe();
            mSubscriber = null;
        }
    }
}
